package com.vehicle.admin.web.common.shiro.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

@Component
public class RoleFilter extends AccessControlFilter {

    private static final String LOGIN_URL="/home/login";
    private static final String UNAUTHORIZED_URL="/common/unauthorized";

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
         String[] array=(String[])o;

        Subject subject=getSubject(servletRequest,servletResponse);
        for(String role:array){
            if(subject.hasRole("role:"+role)){
                return true;
            }
        }
        return false;
    }



    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        Subject subject=getSubject(servletRequest,servletResponse);
        if(subject.getPrincipal()==null){
            saveRequest(servletRequest);
            WebUtils.issueRedirect(servletRequest,servletResponse,LOGIN_URL);
        }else{
            if(StringUtils.hasText(UNAUTHORIZED_URL)){
                WebUtils.issueRedirect(servletRequest,servletResponse,UNAUTHORIZED_URL);
            }else{
                WebUtils.toHttp(servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }

        return false;
    }
}
